import { RouteRecordRaw } from 'vue-router';
import strategy from '@/router/libs/silkBag';

export default async function usePatchOptions(routes: RouteRecordRaw[]) {
  const oprionsUrl = import.meta.glob('@/pages/**/routeOptions.ts');
  const keyList = Object.keys(oprionsUrl);

  for await (const item of keyList) {
    const urlArr = item.split('/').reverse();
    let name = urlArr[1];
    let option = (await import(item)).default;
    let routeOptions = option.routeOptions;
    let otherOptions = option.otherOptions;

    let mapRoutes = routes;
    let index = urlArr.length - 4;
    while (index > 0) {
      if (index === 1) {
        const route = mapRoutes.find((item) => item.name === name);

        strategy.silkBag.patchRouteOptions(route, routeOptions);
        strategy.silkBag.patchOtherOptions(route, otherOptions);
      } else {
        let findRoute = mapRoutes.find((item) => item.name === urlArr[index]);
        mapRoutes = findRoute?.children as RouteRecordRaw[];
      }

      index--;
    }
  }
}
